$(function () {
    $("#dms-execute").on("click",".execute-link",function () {

        var inputParameter = $(this).parents(".execute-group").find(".input-parameter");
        var parameter = JSON.parse(inputParameter.find("textarea[name='inputParameter']").val().replace(/\n/g,"\n").replace(/\r/g,"\r"));
        var url = $(this).text();
        var queryString = JSON.param(parameter);
      //  url += "?" + queryString;

        openWindow(url,parameter);
        //window.open(url);
    });

    //执行
    $("#dms-execute").on("click",".execute",function () {
        var _this = this;
        var index = $(this).attr("index");
        var data = {
            dataSourceCodes : $("#dataSourceCodes").val(),
            namespace : $("#namespace").val(),
            sqlStatement :  $("#mappedStatement").data("codeMirror").getValue(),
            parses : getMappedStatementApiData(index),
            "operate" : "执行"
        };
        $.ajax({
            url: "/dms/test",
            data: JSON.stringify(data),
            method: "post",
            dataType: "json",
            contentType: 'application/json',
            success: function (data) {
                renderMappedStatement(data,index);
                $("#dms-execute-tab").trigger("click");
            },
            error : function (XMLHttpRequest,textStatus,errorThrown) {
                var textarea = $(_this).parents(".execute-group").find("textarea[name='outParameter']");
                textarea.removeClass("alert-success").addClass("alert-danger");
                textarea.val(XMLHttpRequest.responseText);
            }
        });
    });
});


function renderMappedStatementExecuteResult(data,index) {
    $("#dms-execute-tab").trigger("click");
    if(!Array.isArray(data) || data.length < 1){ return ;}

    var execute = $("#dms-execute");
    var outParameter = execute.find("textarea[name='outParameter']");
    if(index === 0 || index){
        var result = data[0];
        var textarea = outParameter.eq(index);
        if(result.status){
            textarea.removeClass("alert-danger").addClass("alert-success");
        }else {
            textarea.removeClass("alert-success").addClass("alert-danger");
        }
        textarea.val(JSON.stringify(result.result,null,4));
    }else {
        for(var i = 0 ; i < data.length ;i++){
            var textarea =  $(outParameter[i]);
            var result = data[i];
            if(result.status){
                textarea.removeClass("alert-danger").addClass("alert-success");
            }else {
                textarea.removeClass("alert-success").addClass("alert-danger");
            }
            textarea.val(JSON.stringify(result.result,null,4));
        }
    }
}

function renderMappedStatementExecute(array) {
    var html = [];
    for(var i  = 0 ; i < array.length ; i++){
        html.push("<div class='execute-group'>");
        html.push("<div class='col-sm-12 execute-mappedStatement'><span class='execute-key' >请求地址:");
        html.push("<a class='execute-value btn btn-link execute-link' index ='"+i+"'>/"+(array[i].id.replace(/\./g,"/"))+"</a>");
        html.push("</div>");
        html.push(renderMappedStatementExecuteBody(array[i],i).join(""));
        html.push("</div>");
    }
    $("#dms-execute").data("execute",array);
    $("#dms-execute .execute-container").html(html.join(""));


    //设置参数输入框高度
    var height =  ($(document).height() - $(".dms").offset().top -50) / 2;

    $(".execute-container").find("textarea").height(height);

}

function renderMappedStatementExecuteBody(parameter,index){
    var html = [];
    var inputParameter =  parameter.inputParameterMock;//API.mock({data:parameter.parameterFields});
    html.push("<div class='col-sm-12 execute-parameter'>");

    html.push("<div class='input-parameter'>");
    html.push("<span class='execute-key' >请求参数</span><button type='button'  class='btn btn-link execute' index='"+index+"'>执行</button>");
    html.push("<input type='hidden' name='shortId' value='"+parameter.shortId+"'/>");
    html.push("<textarea class='form-control' name='inputParameter'  placeholder='json参数'>"+JSON.stringify(inputParameter,null,4)+"</textarea>");
    html.push("</div>");

    html.push("<div class='output-parameter'>");
    html.push("<span class='execute-key' >响应参数</span>");
    html.push("<textarea class='form-control' name='outParameter'  placeholder='响应结果'></textarea>");
    html.push("</div>");

    html.push("</div>");
    return html;
}


function openWindow(url,parameter) {
    $.ajax({
        url: url,
        data: JSON.stringify(parameter),
        method: "post",
        dataType: "json",
        contentType: 'application/json',
        success: function (data) {
            var win = window.open("_blank");
            win.location = "/pages/dms/black.html";
            win.onload = function (ev) {
                win.history.replaceState("", "", url);
                win.document.getElementById("url").value = url;
                var preInput = win.document.getElementById('parameter');
                preInput.innerHTML = JSON.stringify(parameter,null,4);
                //win.document.body.appendChild(preInput);

                var preOutput = win.document.getElementById('result');
                preOutput.innerHTML = JSON.stringify(data,null,4);
                // win.document.body.appendChild(preOutput);
            }

        }
    });
}